﻿namespace _39_C_中lock关键字
{
    internal class Program
    {
        private static readonly object _lock = new object();

        private static int num = 0;//不能放int 可以 (object)num 用string 类型会有驻留机制发生死锁

        private static List<string> strings = new List<string>();

        static void Main(string[] args)
        {
            Console.Title = "C#中lock关键字";

            //lock (_lock)//这个里面是个object对象
            //{
            //    num++;
            //}//逻辑运行完成再释放
            //Console.WriteLine(num);

            //等价于
            //Monitor.Enter(_lock);
            //try
            //{
            //    num++;
            //}
            //finally
            //{
            //    Monitor.Exit(_lock);
            //}
            //Console.WriteLine(num);

            Thread thread = new Thread(new ThreadStart(show));
            Thread thread1 = new Thread(new ThreadStart(show));
            Thread thread2 = new Thread(new ThreadStart(show));
            Thread thread3 = new Thread(new ThreadStart(show));
            Thread thread4 = new Thread(new ThreadStart(show));

            thread.Start();
            thread1.Start();
            thread2.Start();
            thread3.Start();
            thread4.Start();

            Console.Read();

            foreach (var item in strings)
            {
                Console.WriteLine(item);
            }

            Console.ReadKey();
        }

        private static void show()
        {
            //lock (_lock)
            //{
            //    strings.Add(DateTime.Now.ToString());

            //    Thread.Sleep(1000);
            //}

            //等价于
            Monitor.Enter(_lock);
            try
            {
                strings.Add(DateTime.Now.ToString());
                Thread.Sleep(1000);
            }
            finally
            {
                Monitor.Exit(_lock);
            }
        }
    }
}
